package com.fjh.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.fjh.constant.SysRoleConstant;
import com.fjh.domain.SysRole;
import com.fjh.mapper.SysRoleMapper;
import com.fjh.service.SysRoleService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.time.Duration;
import java.util.List;

@Service
@Slf4j
public class SysRoleServiceImpl extends ServiceImpl<SysRoleMapper, SysRole> implements SysRoleService{

    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Autowired
    private StringRedisTemplate redisTemplate;

    public List<SysRole> list(){
        String roleStr = redisTemplate.opsForValue().get(SysRoleConstant.SYS_ROLE_PREFIX);
        List<SysRole> sysRoles = null;
        if (StringUtils.hasText(roleStr)){
            sysRoles = JSON.parseArray(roleStr,SysRole.class);
        }else {
            sysRoles = sysRoleMapper.selectList(null);
            if (!CollectionUtils.isEmpty(sysRoles)){
                redisTemplate.opsForValue().set(SysRoleConstant.SYS_ROLE_PREFIX, JSON.toJSONString(sysRoles), Duration.ofDays(7));
            }
        }
        return sysRoles;
    }

}
